<template>
  <el-dialog
    :visible="visible"
    :before-close="closeDialog"
    title="活动二维码认证"
    width="50%">
    <div>
      <h1>请使用手机扫一扫功能，扫描识别当前活动二维码。</h1>
      <p>当前二维码生成时间：{{ dateTime }}</p>
    </div>
    <div class="qrcode-box" style="text-align: center">
      <canvas ref="canvas" :class="{'blur' : !canScan}"/><br>
      <el-button @click="getCode">刷新验证码</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getAdminActivityCode } from '@/api/activity'
import QRCode from 'qrcode'

export default {
  name: 'QrcodeDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    activity: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      code: null,
      url: null,
      dateTime: null,
      timer: null,
      AcId: null,
      canScan: true,
      context: window.location.origin
    }
  },
  watch: {
    visible: function() {
      if (this.visible) {
        this.getCode()
      }
    }
  },
  created() {
    this.AcId = this.$route.params.id.toString()
  },
  methods: {
    getCode() {
      getAdminActivityCode(this.AcId).then(res => {
        if (res.code === 200) {
          this.code = encodeURIComponent(window.btoa(res.data))
          const url = window.location.origin + this.$route.path + '?verifycode=' + this.code
          this.genQrcode(url)
        } else {
          this.$message({ type: 'error', message: res.msg })
          this.canScan = true
        }
      }).catch(() => {})
    },
    genQrcode(text) {
      const self = this
      const canvas = this.$refs.canvas
      QRCode.toCanvas(canvas, text, { width: 300 }, function(error) {
        self.dateTime = self.getNowDate()
        if (error) console.error(error)
        self.startBlur()
      })
    },
    startBlur() {
      clearTimeout(this.timer)
      this.canScan = true
      this.timer = setTimeout(() => {
        this.canScan = false
      }, 180000)
    },
    getNowDate() {
      var date = new Date()
      var sign1 = '-'
      var sign2 = ':'
      var year = date.getFullYear() // 年
      var month = date.getMonth() + 1 // 月
      var day = date.getDate() // 日
      var hour = date.getHours() // 时
      var minutes = date.getMinutes() // 分
      var seconds = date.getSeconds() // 秒
      // 给一位数数据前面加 “0”
      if (month >= 1 && month <= 9) {
        month = '0' + month
      }
      if (day >= 0 && day <= 9) {
        day = '0' + day
      }
      if (hour >= 0 && hour <= 9) {
        hour = '0' + hour
      }
      if (minutes >= 0 && minutes <= 9) {
        minutes = '0' + minutes
      }
      if (seconds >= 0 && seconds <= 9) {
        seconds = '0' + seconds
      }
      var currentdate = year + sign1 + month + sign1 + day + ' ' + hour + sign2 + minutes + sign2 + seconds
      return currentdate
    },
    closeDialog() {
      this.$emit('close')
    }
  }
}
</script>

<style scoped>
.blur {
  -ms-filter: blur(5px);
  filter: blur(5px);
}
</style>
